<?php
/**
 * 【重要】CCache
 * Enter description here ...
 * @author hxm
 *
 */
class CCache {
	
	public static $type = '.html';
	
	public static $runtimeFile = null;
	
	public static $enable = true;   //是否启用数据压缩
	
	public static $expire = 300;    //缓存过期时间(默认为5分钟) 
	
	/**
	 * 写入缓存
	 * Enter description here ...
	 * @param unknown_type $html
	 */
	public static function setcache($html,$val) {
		$runtimeFile = self::getFileKey($html);//缓存文件初始化
		if(!file_exists($runtimeFile)) {
			SoftBase::mkfile($runtimeFile);
		}
		if($runtimeFile) {
			$data = serialize($val);
			if(self::$enable && function_exists('gzcompress')) {
				$data = gzcompress($data,3);
			}
			$bool = file_put_contents($runtimeFile,$data);
			if($bool) {
				clearstatcache();
				return true;
			} else {
				return false;
			}
		}
	}
	
	/**
	 * 获取缓存
	 * Enter description here ...
	 * @param unknown_type $key
	 */
	public static  function getcache($key) {
		$filename = self::getFileKey($key);
		if(!file_exists($filename)) return null;
		if(time() - filemtime($filename) >= self::$expire)
		{
			@unlink($filename);
			return null;
		}
		$data = file_get_contents($filename);
		if(empty($data)) return null;
		
		if(self::$enable && function_exists('gzcompress'))
		{
			$data = gzuncompress($data);
		}
		return unserialize($data);
	}
	
	/**
	 * 文件检查
	 * Enter description here ...
	 * @param unknown_type $key
	 */
	private static function getFileKey($key) {
		
		return SoftBase::$config['basePath'].'runtime/'.md5($key).self::$type;
	}
	
	/**
	 * 装载模板文件并返回解析后的html
	 *
	 * @access	public
	 * @param	string	$file	文件名
	 * @return	string
	 */
	public static function fetch($file = null)
	{
		ob_start();
		require($file);
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}
}
